#include "MuWinTitlebar.h"
#include <QEvent>
#include <QPushButton>

#include "MuWinWindow.h"
#include "./ui_MuWinTitlebar.h"


MuWinTitlebar::MuWinTitlebar(QWidget *parent)
    : QWidget(parent),
    ui(new Ui::MuWinTitlebar)
{
    ui->setupUi(this);

    connect(ui->btnMinimize, &QPushButton::clicked, this, &MuWinTitlebar::ShowMinimized);
    connect(ui->btnClose, &QPushButton::clicked, this, &MuWinTitlebar::Close);
    connect(ui->btnMaxmize, &QPushButton::clicked, [this](bool checked)
        {
            if (checked)
                emit ShowMaximized();
            else
                emit ShowRestoreSize();
        }
    );
}

bool MuWinTitlebar::eventFilter(QObject *watched, QEvent *event)
{
    MuWinWindow *window = qobject_cast<MuWinWindow *>(watched);
    if (window == nullptr)
        return false;

    switch (event->type()) {
    case QEvent::Resize: {
        if (window->isMaximized()) {
            ui->btnMaxmize->setChecked(true);
        } else {
            ui->btnMaxmize->setChecked(false);
        }
        return true;
    }

    default:
        break;
    }
    return QWidget::eventFilter(watched, event);
}

//void MuWinTitlebar::resizeEvent(QResizeEvent *e)
//{
//    QRegion reg(frameGeometry());
//    reg -= QRegion(geometry());
//    reg += childrenRegion();
//    //reg -= ui->label->geometry();
//    setMask(reg);
//    QWidget::resizeEvent(e);
//}

QRegion MuWinTitlebar::GetProperRegion() const
{
    auto rect = frameGeometry();
    rect = rect.adjusted(4, 4, -4, 0);

    QRegion reg(rect);
    for (const auto* obj : children())
    {
        auto btn = qobject_cast<const QPushButton*>(obj);
        if (!btn) continue;
         
        reg -= btn->geometry();
    }

    return reg;
}

